package store

import (
	"encoding/json"
	"fmt"
	"github.com/pkg/errors"
	"learn/smart/fetcher"
	"learn/smart/config"
)

type ItemResult struct {
	Status int
	Data   Data
}

type Data struct {
	List    []Item
	Total   int
	Page    int
	Message string
}

type Item struct {
	Id           int
	Item_Id      int
	Product_Type string
	Price        float64
	Name         string
	Appid        int
	Num          int
}

var f fetcher.Fetcher

func Search(name string, appid int) ([]Item, error) {
	if f.BaseUrl == "" {
		f = fetcher.Fetcher{BaseUrl: config.GetOpenC5gameUrl()}
	}
	var result ItemResult

	path := fmt.Sprintf("/v1/store?appid=%d&keyword=%s&limit=%d", appid, name, 50)
	resp, err := f.Get(path, nil)
	if err != nil {
		return result.Data.List, err
	}
	defer resp.Body.Close()

	contents, err := fetcher.GetContents(resp)

	if err != nil {
		return result.Data.List, err
	}

	json.Unmarshal(contents, &result)

	if result.Status != 200 {
		return result.Data.List, errors.New(result.Data.Message)
	}

	return result.Data.List, nil
}
